﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CashFlow.Entities;
using CashFlow.Entities.Models;
using CashFlow.Repository;
using CashFlow.AzureRepository;
using System.Web.Routing;
using System.Diagnostics;
using System.Threading.Tasks;

namespace CashFlow.Web.Controllers
{
	public class TenantController : Controller
	{
		private ITenantRepository repository;

		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="T:TenantController"/> class.
		/// </summary>
		public TenantController()
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:TenantController"/> class.
		/// </summary>
		public TenantController(ITenantRepository repository)
		{
			this.repository = repository;
		}
		
		/// <summary>
		/// 
		/// </summary>
		/// <param name="requestContext"></param>
		protected override void Initialize(RequestContext requestContext)
		{
			if (repository == null)
			{
				repository = new AzureTenantRepository();
			}
			base.Initialize(requestContext);
		}
		#endregion
		//
		// GET: /Tenant/

		public ActionResult Index()
		{
			return View();
		}

		#region Balance
						
		[HttpGet]
		public ActionResult InitialBalance()
		{
			//var model = FakeDataProvider.FakeTenant.BalanceModel();
			var tenant = repository.GetById();
			var model = (InitialBalanceEditModel)tenant;
			return View("InitialBalance", model);
		}

		[HttpPost]
		public ActionResult InitialBalance(InitialBalanceEditModel model)
		{
			ActionResult result = View(model);
			if (ModelState.IsValid)
			{
				SaveToRepository(model);
				result = RedirectToAction("Index", "CashFlow");
			}

			return result;
		}

		private void SaveToRepository(InitialBalanceEditModel model)
		{
			Tenant tenant = null;
			try
			{
				tenant = (Tenant)model;
				tenant.Id = AppState.TenantId;
				repository.UpdateBalance(tenant);
			}
			catch (Exception exc)
			{
				//Trace.TraceError(
				//  "ERROR: {0} | {1} | {2} | {3} | {4} ",
				//  this.GetType().FullName,
				//  System.Reflection.MethodBase.GetCurrentMethod().Name,
				//  "Exception",
				//  exc,
				//  tenant);
				//TODO: vvs p2 log & submit error to error handler.
				//ModelState.AddModelError("", Properties.Resources.ErrorModelSave);
			}
		}
	#endregion	
	}
}
